const fs = require('fs')
const path = require('path')

const srcpath = path.resolve('src', 'components', 'articles')
const destfile = path.resolve('src', 'router', 'articles.js')
const componentpath = path.join('@', 'components', 'articles')

const writeable = fs.createWriteStream(destfile)

function toCamel (str) {
  const len = str.lastIndexOf('.vue')
  return str[0].toUpperCase() + str.slice(1, len)
}

fs.readdir(srcpath, (err, filelist) => {
  if (err) throw err
  for (let d of filelist) {
    let filename = toCamel(d)
    writeable.write(`import ${filename} from '${componentpath}/${d}'\n`)
  }
  writeable.write('\n')

  writeable.write('const routes = [\n')
  writeable.write('  { path: \'\', redirect: \'xiangjixuanzhi\' },\n')
  for (let i = 0; i < filelist.length; i++) {
    const d = filelist[i]
    const name = toCamel(d)
    writeable.write('  {\n')
    writeable.write(`    component: ${name},\n`)
    writeable.write(`    path: '${name.toLowerCase()}'\n`)
    writeable.write('  }')
    if (i < filelist.length - 1) {
      writeable.write(',\n')
    } else {
      writeable.write('\n')
    }
  }
  writeable.write(']\n\n')

  writeable.write('export default routes\n')

  writeable.end()
})
